package com.hankol.material.viewmodel

import android.app.Activity
import android.graphics.drawable.BitmapDrawable
import android.view.*
import android.widget.*
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.RecyclerView
import com.baselibrary.MessageBus
import com.baselibrary.bean.ShareItemBean
import com.baselibrary.manager.LoadingManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.net.APIResponse
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.hankol.material.R
import com.hankol.material.adapter.MaterialFolderAdapter
import com.hankol.material.api.MaterialConstants
import com.hankol.material.bean.CreateFolderBean
import com.hankol.material.bean.FolderListBean
import com.hankol.material.bean.MaterialBusinessBean
import com.hankol.material.bean.TabConfigure
import com.hankol.material.respository.MaterialReqManager

/**
 * @author: 关忆北丶
 * @time: 2021/10/25 11:49
 * @description: 素材庫公共model
 */
open class MaterialBaseViewModel : ViewModel() {
    var createFolderListener: CreateFolderListener? = null
    var onMaterialLoadCompleteListener: OnMaterialLoadCompleteListener? = null

    var folderListResultBean: MutableLiveData<List<FolderListBean>> = MutableLiveData()

    var createResultBean: MutableLiveData<CreateFolderBean> = MutableLiveData()

    var addFileToFolderResultBean: MutableLiveData<CreateFolderBean> = MutableLiveData()

    var deleteFolderResultBean: MutableLiveData<Boolean> = MutableLiveData()

    var renameFolderResultBean: MutableLiveData<Boolean> = MutableLiveData()


    fun shareMaterial(activity: Activity, fId: Long, fileName: String, cover: String, isImg: Boolean, fileType: Int) {
        var shareType: String = ""
        reqMaterialAuthenticity(fId, object : APIResponse<Boolean>(this) {
            override fun onSuccess(result: Boolean?, json: String?) {
                var shareContent = ""
                when (fileType) {
                    TabConfigure.FILE.tabConfig -> {
                        shareContent = "素材库分享文件-${fileName}"
                        shareType = MaterialConstants.MATERIAL_FILE
                    }
                    TabConfigure.VIDEO.tabConfig -> {
                        shareContent = "素材库分享视频-${fileName}"
                        shareType = MaterialConstants.MATERIAL_VIDEO
                    }
                    TabConfigure.IMG.tabConfig -> {
                        shareContent = "素材库分享图片-${fileName}"
                        shareType = MaterialConstants.MATERIAL_IMG
                    }
                }
                ShareManager.showSharePopWindow(activity, AppUtils.getSaveShareHostUrl() + "/html/photoesWarehouse/photoShare.html?fid=" + fId, cover, fileName, shareContent, object : SharePopupWindow.OnShareClickListener {
                    override fun onShareClick(type: Int) {
                        when (type) {
                            ShareItemBean.WX -> {
                                SensorsDataManager.instance.materialShare(fileName,shareType,"微信好友")
                            }
                            ShareItemBean.WXZone -> {
                                SensorsDataManager.instance.materialShare(fileName,shareType,"朋友圈")
                            }
                        }
                    }
                    override fun onShareFriendClick(bean: ShareItemBean) {}
                })?.setShareItem(false, false, false, false)
                reqAddShareCount(fId, 1)
            }
        })
    }

    /**
     * 获取资料夹列表
     */
    fun getFolderList() {
        MaterialReqManager.getInstance().getFolderList(folderListResultBean)
    }

    /**
     * 创建资料夹
     */
    fun createFolder(folderName: String) {
        MaterialReqManager.getInstance().createFolder(createResultBean, folderName)
    }


    /**
     * 增加文件到资料夹
     */
    fun addFileToFolder(fileId: Long, folderId: Long, apiResponse: APIResponse<CreateFolderBean>) {
        MaterialReqManager.getInstance().addFileToFolder(fileId, folderId, apiResponse)
    }

    /**
     * 删除资料夹
     */
    fun deleteFolder(folderId: Long) {
        MaterialReqManager.getInstance().deleteFolder(deleteFolderResultBean, folderId)
    }

    /**
     * 重命名资料夹
     */
    fun renameFolder(folderNewName: String, folderId: Long) {
        MaterialReqManager.getInstance().renameFolder(renameFolderResultBean, folderNewName, folderId)
    }

    /**
     * 转移资料夹
     */
    fun loadMoveFolder(fid: Long, newCid: Long, oldCid: Long, apiResponse: APIResponse<Boolean>) {
        MaterialReqManager.getInstance().loadMoverFolder(fid, newCid, oldCid, apiResponse)
    }

    /**
     * 取消收藏
     */
    fun loadCancelCollection(cid: Long, fid: Long, apiResponse: APIResponse<Boolean>) {
        reqMaterialAuthenticity(fid, object : APIResponse<Boolean>(this) {
            override fun onSuccess(result: Boolean?, json: String?) {
                MaterialReqManager.getInstance().cancelCollection(cid, fid, apiResponse)
            }

        })
    }

    /**
     * 素材是否存在
     */
    fun reqMaterialAuthenticity(fid: Long, apiResponse: APIResponse<Boolean>) {
        MaterialReqManager.getInstance().reqMaterialAuthenticity(fid, object : APIResponse<Boolean>(this) {
            override fun onSuccess(result: Boolean, json: String) {
                if (result) {
                    apiResponse.onSuccess(result, json)
                } else {
                    HKToastUtils.showToast("内容已删除")
                }
            }

            override fun onFailed(message: String?) {
                //  ToastUtils.showShort(HKUtils.getApp().applicationContext, "内容已删除")
            }
        })
    }


    /**
     * 增加分享/下载数量
     */
    fun reqAddShareCount(fid: Long, type: Int) {
        MaterialReqManager.getInstance().reqAddShareCount(fid, type)
    }


    /**
     * 收藏
     * @param isCollection true = 添加到收藏夹
     * @param fileId 文件ID
     *
     */
    fun collectionMaterial(activity: Activity, owner: LifecycleOwner, fileId: Long, apiResponse: APIResponse<CreateFolderBean>) {

        reqMaterialAuthenticity(fileId, object : APIResponse<Boolean>(activity) {
            override fun onSuccess(result: Boolean?, json: String?) {
                val showCollectionMaterialView = LayoutInflater.from(activity).inflate(R.layout.popup_material_folder, null)
                val materialPop = showCollectionMaterial(activity, showCollectionMaterialView)
                val pbCollection = showCollectionMaterialView.findViewById<ProgressBar>(R.id.pb_collection)
                val rvCollection = showCollectionMaterialView.findViewById<RecyclerView>(R.id.rv_collection)
                val llCollectionAdd = showCollectionMaterialView.findViewById<LinearLayout>(R.id.ll_collection_add)

                llCollectionAdd.visibility = View.VISIBLE

                val layoutParams = showCollectionMaterialView.layoutParams
                layoutParams.height = ScreenUtils.getScreenHeight() / 3
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
                showCollectionMaterialView.layoutParams = layoutParams

                val mAdapter = MaterialFolderAdapter()

                folderListResultBean.observe(owner, Observer {
                    if (!materialPop.isShowing) {
                        folderListResultBean.removeObservers(owner)
                        return@Observer
                    }
                    pbCollection.visibility = View.GONE
                    rvCollection.visibility = View.VISIBLE
                    rvCollection.adapter = mAdapter
                    setLayoutParams(layoutParams, it, activity, showCollectionMaterialView)
                    mAdapter.setNewData(it)
                    folderListResultBean.removeObservers(owner)
                })

                llCollectionAdd.setOnClickListener {
                    if (!HKUtils.isFastClick()) return@setOnClickListener
                    //新建文件夹
                    ActivityRouter.startActivity(ActivityRouter.MATERIAL.MATERIAL_CREATE_FOLDER)
                }

                mAdapter.setOnItemClickListener { adapter, view, position ->
                    val folderListBean = adapter.data[position] as FolderListBean
                    addFileToFolder(fileId, folderListBean.id, apiResponse)
                    materialPop.dismiss()
                }

                createFolderListener = object : CreateFolderListener {
                    override fun onCreateFolder(bean: FolderListBean) {
                        mAdapter.addData(bean)
                        setLayoutParams(layoutParams, mAdapter.data, activity, showCollectionMaterialView)
                    }
                }
                getFolderList()

            }
        })

    }

    /**
     * 转移
     *
     */
    fun moveMaterial(activity: Activity, owner: LifecycleOwner, fileId: Long, oldCid: Long, apiResponse: APIResponse<Boolean>) {
        reqMaterialAuthenticity(fileId, object : APIResponse<Boolean>(this) {
            override fun onSuccess(result: Boolean?, json: String?) {
                val showCollectionMaterialView = LayoutInflater.from(activity).inflate(R.layout.popup_material_folder, null)
                val materialPop = showCollectionMaterial(activity, showCollectionMaterialView)
                val pbCollection = showCollectionMaterialView.findViewById<ProgressBar>(R.id.pb_collection)
                val rvCollection = showCollectionMaterialView.findViewById<RecyclerView>(R.id.rv_collection)
                val llCollectionAdd = showCollectionMaterialView.findViewById<LinearLayout>(R.id.ll_collection_add)
                val rlCollection = showCollectionMaterialView.findViewById<RelativeLayout>(R.id.rl_collection)

                llCollectionAdd.visibility = View.GONE

                val layoutParams = showCollectionMaterialView.layoutParams
                layoutParams.height = ScreenUtils.getScreenHeight() / 3
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
                showCollectionMaterialView.layoutParams = layoutParams

                val mAdapter = MaterialFolderAdapter()

                folderListResultBean.observe(owner, Observer {
                    if (!materialPop.isShowing) {
                        folderListResultBean.removeObservers(owner)
                        return@Observer
                    }
                    pbCollection.visibility = View.GONE
                    rvCollection.visibility = View.VISIBLE
                    rvCollection.adapter = mAdapter
                    setLayoutParams(layoutParams, it, activity, showCollectionMaterialView)
                    mAdapter.setNewData(it)
                    folderListResultBean.removeObservers(owner)
                })

                llCollectionAdd.setOnClickListener {
                    if (!HKUtils.isFastClick()) return@setOnClickListener
                    //新建文件夹
                    ActivityRouter.startActivity(ActivityRouter.MATERIAL.MATERIAL_CREATE_FOLDER)
                }

                mAdapter.setOnItemClickListener { adapter, view, position ->
                    val folderListBean = adapter.data[position] as FolderListBean
                    if (folderListBean.id == oldCid) {
                        materialPop.dismiss()
                        return@setOnItemClickListener
                    }
                    loadMoveFolder(fileId, folderListBean.id, oldCid, apiResponse)
                    EventBusUtils.sendNotify(MessageBus.msgId_material_moveCollection)
                    materialPop.dismiss()
                }

                createFolderListener = object : CreateFolderListener {
                    override fun onCreateFolder(bean: FolderListBean) {
                        mAdapter.addData(bean)
                        setLayoutParams(layoutParams, mAdapter.data, activity, showCollectionMaterialView)
                    }
                }
                getFolderList()
            }

        })

    }


    private fun setLayoutParams(layoutParams: ViewGroup.LayoutParams, list: List<FolderListBean>, activity: Activity, showCollectionMaterialView: View) {
        //118 是弹窗的【标题栏】 和 【添加收藏夹】高度
        layoutParams.height = (if (list.size > 5) 5 * ScreenUtils.dip2px(activity, 60f) else list.size * ScreenUtils.dip2px(activity, 60f)) + ScreenUtils.dip2px(activity, 118f)
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
        showCollectionMaterialView.layoutParams = layoutParams
    }

    /**
     * 收藏素材
     *
     * @param activity
     */
    fun showCollectionMaterial(activity: Activity, contentView: View): PopupWindow {
        val popupWindow = PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val lp = activity.window.attributes
        lp.alpha = 0.5f
        activity.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        activity.window.attributes = lp

        contentView.findViewById<LinearLayout>(R.id.ll_collection_close).setOnClickListener {
            if (popupWindow.isShowing)
                popupWindow.dismiss()
        }
        popupWindow.setBackgroundDrawable(BitmapDrawable())
        popupWindow.isOutsideTouchable = true//点击外部消失
        popupWindow.isFocusable = true// 取得焦点
        popupWindow.isTouchable = true//设置可以点击
        popupWindow.animationStyle = R.style.camera_popwindow_anim_style
        popupWindow.setOnDismissListener {
            val lpWindow = activity.window.attributes
            lpWindow.alpha = 1f
            activity.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            activity.window.attributes = lpWindow
        }
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0)
        return popupWindow
    }


    /**
     *下载文档
     * @param activity
     */
    fun showDownloadFile(isCollection: Boolean, bean: MaterialBusinessBean, folderName: String, activity: Activity, onClickListener: View.OnClickListener): PopupWindow {
        val downloadFileView = LayoutInflater.from(activity).inflate(R.layout.popup_material_downloadfile, null)
        val popupWindow = PopupWindow(downloadFileView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val lp = activity.window.attributes
        lp.alpha = 0.5f
        activity.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        activity.window.attributes = lp

        val mLlFileDet = downloadFileView.findViewById<LinearLayout>(R.id.ll_file_det)
        val mLlFileMove = downloadFileView.findViewById<LinearLayout>(R.id.ll_file_move)
        val mLlFileCollection = downloadFileView.findViewById<LinearLayout>(R.id.ll_file_collection)
        val mIvFileCollectionLike = downloadFileView.findViewById<ImageView>(R.id.iv_fileCollection_like)


        downloadFileView.findViewById<TextView>(R.id.tv_file_name).text = folderName
        downloadFileView.findViewById<LinearLayout>(R.id.ll_file_download).setOnClickListener {
            popupWindow.dismiss()
            onClickListener.onClick(it)
        }
        mLlFileCollection.setOnClickListener {
            popupWindow.dismiss()
            onClickListener.onClick(it)
        }
        downloadFileView.findViewById<LinearLayout>(R.id.ll_file_share).setOnClickListener {
            popupWindow.dismiss()
            onClickListener.onClick(it)
        }

        mLlFileDet.setOnClickListener {
            popupWindow.dismiss()
            onClickListener.onClick(it)
        }
        mLlFileMove.setOnClickListener {
            popupWindow.dismiss()
            onClickListener.onClick(it)
        }

        if (isCollection) {
            if (bean.type == MaterialConstants.BUSINESS_TYPE_FOLDER) {
                mLlFileMove.visibility = View.VISIBLE
                mLlFileDet.visibility = View.VISIBLE
                mLlFileCollection.visibility = View.GONE
            } else {
                mLlFileMove.visibility = View.GONE
                mLlFileDet.visibility = View.GONE
                mLlFileCollection.visibility = View.VISIBLE
                mIvFileCollectionLike.setImageResource(R.drawable.ic_material_true_like)
            }

        } else {
            mLlFileDet.visibility = View.GONE
            mLlFileMove.visibility = View.GONE
            mLlFileCollection.visibility = View.VISIBLE
        }

        downloadFileView.findViewById<TextView>(R.id.tv_file_cancel).setOnClickListener {
            if (popupWindow.isShowing)
                popupWindow.dismiss()
        }

        popupWindow.setBackgroundDrawable(BitmapDrawable())
        popupWindow.isOutsideTouchable = true//点击外部消失
        popupWindow.isFocusable = true// 取得焦点
        popupWindow.isTouchable = true//设置可以点击
        popupWindow.animationStyle = R.style.camera_popwindow_anim_style
        popupWindow.setOnDismissListener {
            val lpWindow = activity.window.attributes
            lpWindow.alpha = 1f
            activity.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            activity.window.attributes = lpWindow
        }
        popupWindow.showAtLocation(downloadFileView, Gravity.CENTER, 0, 0)
        return popupWindow
    }


    /**
     * 刪除文件夹
     * @param activity
     *
     */
    fun showDeleteFolder(folderId: Long, activity: Activity): PopupWindow {
        val downloadFileView = LayoutInflater.from(activity).inflate(R.layout.popup_deletefolder, null)
        val popupWindow = PopupWindow(downloadFileView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        val lp = activity.window.attributes
        lp.alpha = 0.5f
        activity.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        activity.window.attributes = lp
        downloadFileView.findViewById<TextView>(R.id.tv_det_cancel).setOnClickListener {
            if (popupWindow.isShowing) popupWindow.dismiss()
        }
        downloadFileView.findViewById<TextView>(R.id.tv_det_confirm).setOnClickListener {
            LoadingManager.showLoadingDialog(activity)
            deleteFolder(folderId)
        }

        popupWindow.setBackgroundDrawable(BitmapDrawable())
        popupWindow.isOutsideTouchable = true//点击外部消失
        popupWindow.isFocusable = true// 取得焦点
        popupWindow.isTouchable = true//设置可以点击
        popupWindow.animationStyle = R.style.camera_popwindow_anim_style
        popupWindow.setOnDismissListener {
            val lpWindow = activity.window.attributes
            lpWindow.alpha = 1f
            activity.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            activity.window.attributes = lpWindow
        }
        popupWindow.showAtLocation(downloadFileView, Gravity.CENTER, 0, 0)
        return popupWindow
    }


    interface CreateFolderListener {
        fun onCreateFolder(bean: FolderListBean)
    }

    interface OnMaterialLoadCompleteListener {
        fun onMaterialLoadComplete()
    }

    interface IRightLeftCallBack {
        fun leftClick()
        fun rightClick()
    }
}